package simorg.actions;

import org.dom4j.Document;
import org.dom4j.Element;

import simorg.controller.CourseController;
import simorg.domain.Course;
import simorg.domain.Role;
import simorg.domain.User;
import simorg.domain.persistence.CourseTable;
import simorg.domain.persistence.UserTable;
import simorg.view.ModelView;
import simorg.view.Page;
import simorg.view.WebSessionContext;

public class CourseView extends Action {

	public static final String actionName = "view";
	
	public CourseView() {
		super(actionName);
		this.controllerName = CourseController.controllerName;
	}
	public CourseView(String courseId) {
		super(actionName);
		this.controllerName = CourseController.controllerName;
		this.getRequestArgs().add(courseId);
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		Document xmlDoc = this.getBaseXml(wc);
		Element courseElement = xmlDoc.getRootElement().addElement( "selected-course" );
		int id = Integer.parseInt(this.getRequestArgs().get(0));
		System.out.println("Viewing Course ID = " + id);
		Course course = CourseTable.findById(wc.getDbConnection(), id);
		course.buildDomainXml(courseElement, wc.getDbConnection());
		
		Element availableInstructors = xmlDoc.getRootElement().addElement("available-instructors");
		for ( User instructor : UserTable.findAllByRole(wc.getDbConnection(), Role.Instructor) ) {
			instructor.buildDomainXml(availableInstructors);
		}
		return new ModelView(Page.Course, xmlDoc);
	}

}
